#!/usr/bin/env python3  /*设定脚本文件直接能执行*/
# -*- coding:utf-8 -*-   /*设置编码*/
"""
@Author: zhuo
@Software: PyCharm
@File: tQLoginBox.py
@Time: 2024/1/18 13:39
@Function：ctQLoginBox：自定义登录框，可实现登录、用户新增删除、用户信息更改功能。
"""
import os

from PySide6.QtWidgets import *
from PySide6.QtGui import *
from tBLL.tFileINI import ctFileINI

COSMO_BLUE = "#005AAA"  # 卡奥斯蓝
HAIER_BLUE = "#1296DB"  # 海尔蓝


class ctQLoginBox(QWidget):
    """
    自定义登录框：可实现登录、用户新增删除、用户信息更改功能。
    """

    # 初始化
    def __init__(self):
        """
        function:  初始化
              in:
             out:  None
          return:  None
          others:  Initialize
        """
        # 继承自父类
        super(ctQLoginBox, self).__init__()
        self.setFixedSize(260, 220)
        # 创建Tab
        self.tab = QTabWidget(self)
        self.tab.setFixedSize(260, 220)
        # QTabWidget增加Tab页
        self.tabOne = QWidget()
        self.tabTwo = QWidget()
        self.tabThree = QWidget()
        self.tabFour = QWidget()
        self.tab.addTab(self.tabOne, "one")
        self.tab.addTab(self.tabTwo, "two")
        self.tab.addTab(self.tabThree, "three")
        self.tab.addTab(self.tabFour, "four")
        self.tab.tabBar().hide()
        # 主布局
        self.layoutMain = QVBoxLayout()
        self.layoutMain.addWidget(self.tab)
        # 账号选择框
        self.cbbAccount = QComboBox()
        # 密码文本框
        self.txtPassword = QLineEdit()
        # 账号密码字典：{"超级管理员": {"password": "1", "index": 0, "state": 0}}；state：(0：未登录；1：已登录)
        self.accountDic = {}
        # <editor-fold desc="创建账号文件路径">
        # 获取当前文件所在文件夹路径
        folder_path = os.getcwd()
        # 登录账号密码存放路径
        save_path_dir = f"{folder_path}\\tdata"
        # 判断该路径是否存在
        if not os.path.exists(save_path_dir):
            # 如果不存在则创建
            os.makedirs(save_path_dir)
        # 配置文件存放路径
        self.filePath = save_path_dir + "\\account.ini"
        # 写入ini文件类实例化
        self.configFile = ctFileINI(self.filePath)
        # </editor-fold>
        # 读取配置文件
        self.__f_readFile()
        for key in self.accountDic:
            self.cbbAccount.addItem(key)
        # 新增用户界面账号选择框
        self.cbbAddAccount = QComboBox()
        # 新增用户界面密码文本框
        self.txtAddPassword = QLineEdit()
        # 未登录界面布局函数
        self.__f_notLoginLayoutFunc()
        # 超级管理员登录界面函数
        self.__f_superLoginLayoutFunc()
        # 普通管理员登录界面函数
        self.__f_commonLoginLayoutFunc()
        # 新增用户界面布局函数
        self.__f_addUserLayoutFunc()
        # Tab页切换到未登录界面
        self.tab.setCurrentIndex(0)

    # <editor-fold desc="登录框界面布局函数">
    # 未登录界面布局函数
    def __f_notLoginLayoutFunc(self):
        """
        function:  未登录界面布局函数
              in:  None
             out:  None
          return:  None
          others:  No Login Form Layout Func
        """
        # 未登录主界面：垂直布局
        layoutNotLogin = QVBoxLayout(self.tabOne)
        # 创建图标布局：格栅布局
        lblLayout = QGridLayout()
        # 输入为图片路径，比如ico文件内的icon.png图片
        lblIcon = QLabel()
        lblIcon.setPixmap(QPixmap("./ico/nologin.png"))
        lblIcon.setFixedSize(60, 60)
        # 设置图标自适应
        lblIcon.setScaledContents(True)
        # 创建弹簧控件
        spacer = QSpacerItem(90, 60, QSizePolicy.Expanding, QSizePolicy.Expanding)
        lblLayout.addItem(spacer, 0, 0)
        lblLayout.addItem(spacer, 0, 2)
        lblLayout.addItem(spacer, 1, 0)
        lblLayout.addWidget(lblIcon, 1, 1)
        lblLayout.addItem(spacer, 1, 2)
        lblLayout.addItem(spacer, 2, 0)
        lblLayout.addItem(spacer, 2, 2)
        # 创建账号布局：水平布局
        accountLayout = QHBoxLayout()
        # 创建密码布局：水平布局
        passwordLayout = QHBoxLayout()
        # 创建标签
        lblAccount = QLabel("账号：")
        lblAccount.setFixedSize(40, 20)
        lblPassword = QLabel("密码：")
        lblPassword.setFixedSize(40, 20)

        self.cbbAccount.setFixedSize(120, 20)
        self.txtPassword.setFixedSize(120, 20)
        self.txtPassword.setEchoMode(QLineEdit.Password)
        # 登录按键布局：格栅布局
        btnLayout = QGridLayout()
        # 登录按键
        btnLogin = QPushButton("登录")
        btnLogin.setFixedSize(200, 20)
        btnLogin.clicked.connect(self.__f_btnLoginClicked)
        # 布局添加
        btnLayout.addWidget(btnLogin)
        accountLayout.addWidget(lblAccount)
        accountLayout.addWidget(self.cbbAccount)
        passwordLayout.addWidget(lblPassword)
        passwordLayout.addWidget(self.txtPassword)
        layoutNotLogin.addLayout(lblLayout)
        layoutNotLogin.addLayout(accountLayout)
        layoutNotLogin.addLayout(passwordLayout)
        layoutNotLogin.addLayout(btnLayout)

    # 超级管理员登录界面函数
    def __f_superLoginLayoutFunc(self):
        """
        function:  超级管理员登录界面函数
              in:  None
             out:  None
          return:  None
          others:  Super Administrator Login Form Func
        """
        # 超级管理员登录主界面：垂直布局
        layoutSuper = QVBoxLayout(self.tabTwo)
        # 创建图标布局：格栅布局
        lblLayout = QGridLayout()
        # 输入为图片路径，比如ico文件内的icon.png图片
        lblIcon = QLabel()
        lblIcon.setPixmap(QPixmap("./ico/super.png"))
        lblIcon.setFixedSize(60, 60)
        # 设置图标自适应
        lblIcon.setScaledContents(True)
        # 创建标签
        lblSuper = QLabel("超级管理员")
        # 设置字体为微软雅黑、字体为粗体
        lblSuper.setStyleSheet("font-family: Microsoft YaHei;" "font-weight:bold;")
        # 创建弹簧控件
        spacer = QSpacerItem(90, 60, QSizePolicy.Expanding, QSizePolicy.Expanding)
        lblLayout.addItem(spacer, 0, 0)
        lblLayout.addItem(spacer, 0, 2)
        lblLayout.addItem(spacer, 1, 0)
        lblLayout.addWidget(lblIcon, 1, 1)
        lblLayout.addItem(spacer, 1, 2)
        lblLayout.addItem(spacer, 2, 0)
        lblLayout.addItem(spacer, 2, 2)
        lblLayout.addWidget(lblSuper, 3, 1)
        # 创建密码布局：水平布局
        btnLayout = QHBoxLayout()
        # 新增用户按键
        btnAdd = QPushButton("新增用户")
        btnAdd.clicked.connect(lambda: self.tab.setCurrentIndex(3))
        # 退出按键
        btnAdd.setFixedSize(100, 25)
        btnAdd.setStyleSheet("font-family: Microsoft YaHei;" "font-weight:bold;")
        # 退出按键
        btnExit = QPushButton("退出")
        btnExit.setFixedSize(100, 25)
        btnExit.setStyleSheet("font-family: Microsoft YaHei;" "font-weight:bold;")
        btnExit.clicked.connect(self.__f_btnExitClicked)
        btnLayout.addWidget(btnAdd)
        btnLayout.addWidget(btnExit)
        layoutSuper.addLayout(lblLayout)
        layoutSuper.addLayout(btnLayout)

    # 普通管理员登录界面函数
    def __f_commonLoginLayoutFunc(self):
        """
        function:  普通管理员登录界面函数
              in:  None
             out:  None
          return:  None
          others:  Common Administrator Login Form Func
        """
        # 普通管理员登录主界面：垂直布局
        layoutCommon = QVBoxLayout(self.tabThree)
        # 创建图标布局：格栅布局
        lblLayout = QGridLayout()
        # 输入为图片路径，比如ico文件内的icon.png图片
        lblIcon = QLabel()
        lblIcon.setPixmap(QPixmap("./ico/common.png"))
        lblIcon.setFixedSize(60, 60)
        # 设置图标自适应
        lblIcon.setScaledContents(True)
        # 创建标签
        lblSuper = QLabel("普通管理员")
        # 设置字体为微软雅黑、字体为粗体
        lblSuper.setStyleSheet("font-family: Microsoft YaHei;" "font-weight:bold;")
        # 创建弹簧控件
        spacer = QSpacerItem(90, 60, QSizePolicy.Expanding, QSizePolicy.Expanding)
        lblLayout.addItem(spacer, 0, 0)
        lblLayout.addItem(spacer, 0, 2)
        lblLayout.addItem(spacer, 1, 0)
        lblLayout.addWidget(lblIcon, 1, 1)
        lblLayout.addItem(spacer, 1, 2)
        lblLayout.addItem(spacer, 2, 0)
        lblLayout.addItem(spacer, 2, 2)
        lblLayout.addWidget(lblSuper, 3, 1)
        # 创建密码布局：水平布局
        btnLayout = QHBoxLayout()
        # 普通管理员退出按键
        btnExitCom = QPushButton("退出")
        btnExitCom.setFixedSize(200, 25)
        btnExitCom.setStyleSheet("font-family: Microsoft YaHei;" "font-weight:bold;")
        btnExitCom.clicked.connect(self.__f_btnExitClicked)
        btnLayout.addWidget(btnExitCom)
        layoutCommon.addLayout(lblLayout)
        layoutCommon.addLayout(btnLayout)

    # 新增用户界面布局函数
    def __f_addUserLayoutFunc(self):
        """
        function:  新增用户界面布局函数
              in:  None
             out:  None
          return:  None
          others:  Added User Form Layout Func
        """
        # 新增用户主界面：垂直布局
        layoutAddUser = QVBoxLayout(self.tabFour)
        # 创建图标布局：格栅布局
        lblLayout = QGridLayout()
        # 输入为图片路径，比如ico文件内的icon.png图片
        lblIcon = QLabel()
        lblIcon.setPixmap(QPixmap("./ico/add.png"))
        lblIcon.setFixedSize(60, 60)
        # 设置图标自适应
        lblIcon.setScaledContents(True)
        # 创建弹簧控件
        spacer = QSpacerItem(90, 60, QSizePolicy.Expanding, QSizePolicy.Expanding)
        lblLayout.addItem(spacer, 0, 0)
        lblLayout.addItem(spacer, 0, 2)
        lblLayout.addItem(spacer, 1, 0)
        lblLayout.addWidget(lblIcon, 1, 1)
        lblLayout.addItem(spacer, 1, 2)
        lblLayout.addItem(spacer, 2, 0)
        lblLayout.addItem(spacer, 2, 2)
        # 创建账号布局：水平布局
        accountLayout = QHBoxLayout()
        # 创建密码布局：水平布局
        passwordLayout = QHBoxLayout()
        # 创建标签
        lblAccount = QLabel("账号：")
        lblAccount.setFixedSize(40, 20)
        lblPassword = QLabel("密码：")
        lblPassword.setFixedSize(40, 20)
        # 密码文本框
        self.txtAddPassword.setFixedSize(120, 20)
        # 账号选择框
        self.cbbAddAccount.setFixedSize(120, 18)
        self.cbbAddAccount.setEditable(True)
        for key in self.accountDic:
            self.cbbAddAccount.addItem(key)
        self.cbbAddAccount.currentIndexChanged.connect(self.__f_cbbTextChanged)
        self.txtAddPassword.setText(self.accountDic[self.cbbAddAccount.currentText()]["password"])
        # 登录按键布局：格栅布局
        btnLayout = QGridLayout()
        # 新增按键
        btnAdd = QPushButton("新增")
        btnAdd.setFixedSize(50, 20)
        btnAdd.clicked.connect(self.__f_btnAddClicked)
        # 修改按键
        btnAlter = QPushButton("修改")
        btnAlter.setFixedSize(50, 20)
        btnAlter.clicked.connect(self.__f_btnAddAlartClicked)
        # 删除按键
        btnRemove = QPushButton("删除")
        btnRemove.setFixedSize(50, 20)
        btnRemove.clicked.connect(self.__f_btnRemoveClicked)
        # 退出按键
        btnExit = QPushButton("返回")
        btnExit.setFixedSize(50, 20)
        btnExit.clicked.connect(lambda: self.tab.setCurrentIndex(1))
        # 布局添加
        btnLayout.addWidget(btnAdd, 0, 0)
        btnLayout.addWidget(btnAlter, 0, 1)
        btnLayout.addWidget(btnRemove, 0, 2)
        btnLayout.addWidget(btnExit, 0, 3)
        accountLayout.addWidget(lblAccount)
        accountLayout.addWidget(self.cbbAddAccount)
        passwordLayout.addWidget(lblPassword)
        passwordLayout.addWidget(self.txtAddPassword)
        layoutAddUser.addLayout(lblLayout)
        layoutAddUser.addLayout(accountLayout)
        layoutAddUser.addLayout(passwordLayout)
        layoutAddUser.addLayout(btnLayout)

    # </editor-fold>

    # <editor-fold desc="按键响应函数">
    # 登录按键点击响应事件
    def __f_btnLoginClicked(self):
        """
        function:  登录按键点击响应事件
              in:  None
             out:  None
          return:  None
          others:  Login Button Click Response Func
        """
        account = self.cbbAccount.currentText()
        password = self.txtPassword.text()
        index = self.accountDic[account]["index"]
        # 超级管理员
        if str(index) == "0":
            if self.accountDic[account]["password"] == password:
                self.accountDic[account]["state"] = 1
                self.txtPassword.clear()
                self.tab.setCurrentIndex(1)
            else:
                self.accountDic[account]["state"] = 0
                self.tab.setCurrentIndex(0)
        # 普通管理员
        else:
            if self.accountDic[account]["password"] == password:
                self.accountDic[account]["state"] = 1
                self.txtPassword.clear()
                self.tab.setCurrentIndex(2)
            else:
                self.accountDic[account]["state"] = 0
                self.tab.setCurrentIndex(0)

    # 退出按键点击响应函数
    def __f_btnExitClicked(self):
        """
        function:  退出按键点击响应函数
              in:  None
             out:  None
          return:  None
          others:  Exit Button Click The Response Func
        """
        self.tab.setCurrentIndex(0)
        for key in self.accountDic:
            self.accountDic[key]["state"] = 0

        self.cbbAccount.clear()
        for key in self.accountDic:
            self.cbbAccount.addItem(key)
        self.txtPassword.clear()

        self.cbbAccount.setCurrentIndex(0)

    # </editor-fold>

    # <editor-fold desc="新增用户界面响应函数">
    # 新增界面删除按键点击响应函数
    def __f_btnRemoveClicked(self):
        """
        function:  新增界面删除按键点击响应函数
              in:  None
             out:  None
          return:  None
          others:  Delete Button Click Response Func
        """
        if self.cbbAddAccount.currentText() == "超级管理员":
            QMessageBox.warning(self, "警告", "超级管理员账户不能删除")
        else:
            # 先清空配置文件
            self.__f_clearFile()
            self.accountDic.pop(self.cbbAddAccount.currentText())
            self.__f_writeFile()
            self.cbbAddAccount.clear()
            for key in self.accountDic:
                self.cbbAddAccount.addItem(key)
            self.txtAddPassword.setText(self.accountDic[self.cbbAddAccount.currentText()]["password"])

    # 新增界面选择框文本改变响应函数
    def __f_cbbTextChanged(self):
        """
        function:  新增界面选择框文本改变响应函数
              in:  None
             out:  None
          return:  None
          others:  Combobox Text Change The Response Func
        """
        if self.cbbAddAccount.currentText() != "":
            self.txtAddPassword.setText(self.accountDic[self.cbbAddAccount.currentText()]["password"])

    # 新增界面新增按键点击响应函数
    def __f_btnAddClicked(self):
        """
        function:  新增界面新增按键点击响应函数
              in:  None
             out:  None
          return:  None
          others:  Added Button Click Response Func
        """
        isExisted = False
        length = len(self.accountDic)
        for key in self.accountDic:
            if key == self.cbbAddAccount.currentText():
                isExisted = True
        if not isExisted:
            dic = {self.cbbAddAccount.currentText():
                       {"password": self.txtAddPassword.text(), "index": length, "state": 0}}
            self.accountDic.update(dic)
            self.__f_writeFile()
            self.cbbAddAccount.clear()
            for key in self.accountDic:
                self.cbbAddAccount.addItem(key)
            self.txtAddPassword.setText(self.accountDic[self.cbbAddAccount.currentText()]["password"])
            self.cbbAddAccount.setCurrentIndex(length)

    # 新增界面修改按键点击响应函数
    def __f_btnAddAlartClicked(self):
        """
        function:  新增界面修改按键点击响应函数
              in:  None
             out:  None
          return:  None
          others:  Add Form Modify Button Click Response Func
        """
        isExisted = False
        index = self.cbbAddAccount.currentIndex()
        for key in self.accountDic:
            if key == self.cbbAddAccount.currentText():
                isExisted = True
        if isExisted:
            self.accountDic[self.cbbAddAccount.currentText()]["password"] = self.txtAddPassword.text()
            self.__f_writeFile()
            self.cbbAddAccount.clear()
            for key in self.accountDic:
                self.cbbAddAccount.addItem(key)
            self.cbbAddAccount.setCurrentIndex(index)
            self.txtAddPassword.setText(self.accountDic[self.cbbAddAccount.currentText()]["password"])

    # </editor-fold>

    # <editor-fold desc="配置文件读取函数">
    # 配置文件清除函数
    def __f_clearFile(self):
        """
        function:  配置文件清除函数
              in:  None
             out:  None
          return:  None
          others:  INI File Clear Func
        """
        if len(self.accountDic) > 0:
            for key in self.accountDic:
                dic = {'Section': f'{key}', "FilePath": f"{self.filePath}"}
                self.configFile.f_Clear(dic)

    # 配置文件写入函数
    def __f_writeFile(self):
        """
        function:  配置文件写入函数
              in:  None
             out:  None
          return:  None
          others:  INI File Write Func
        """
        # 写入前先清空
        self.__f_clearFile()
        # 循环写入
        for key in self.accountDic:
            dic = {'Section': f'{key}', 'Option': 'password', 'Value': f'{self.accountDic[key]["password"]}',
                   "FilePath": f"{self.filePath}"}
            self.configFile.f_Create(dic)
            dic = {'Section': f'{key}', 'Option': 'index', 'Value': f'{self.accountDic[key]["index"]}',
                   "FilePath": f"{self.filePath}"}
            self.configFile.f_Create(dic)
            dic = {'Section': f'{key}', 'Option': 'state', 'Value': f'{self.accountDic[key]["state"]}',
                   "FilePath": f"{self.filePath}"}
            self.configFile.f_Create(dic)

    # 配置文件读取函数
    def __f_readFile(self):
        """
        function:  配置文件读取函数
              in:  None
             out:  None
          return:  None
          others:  INI File Read Func
        """
        # 判断配置文件路径是否存在
        if not os.path.exists(self.filePath):
            # 如果不存在，给默认值
            self.accountDic = {"超级管理员": {"password": "1", "index": 0, "state": 0},
                               "普通管理员": {"password": "123456", "index": 1, "state": 0}}
            self.__f_writeFile()
        else:
            dicR = {}
            # 调用Read方法
            self.configFile.f_Read(dicR)
            # SectionList：ini文件中带[]的项的列表
            listSects = dicR['SectionList']
            # 获取列表的长度
            n = len(listSects)
            for i in range(0, n):
                account = listSects[i]
                dicR['Section'] = account
                self.configFile.f_Read(dicR)
                dicR = dicR['OptionDic']
                self.accountDic[f"{account}"] = {"password": f"{dicR['password']}",
                                                 "index": f"{dicR['index']}",
                                                 "state": f"{dicR['state']}"}
    # </editor-fold>
